/**
 * @package 全局权限验证守卫, 用于验证登录
 * @author liu
 */

import { ExecutionContext, Injectable } from '@nestjs/common'
import { AuthGuard } from '@nestjs/passport'
import { Reflector } from '@nestjs/core'
import type { Request } from 'express'
import { Observable } from 'rxjs'

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  constructor(private reflector: Reflector) {
    super()
  }

  canActivate(
    ctx: ExecutionContext
  ): boolean | Promise<boolean> | Observable<boolean> {
    console.log('全局权限验证守卫, 用于验证登录')
    const request: Request = ctx.switchToHttp().getRequest()
    // 放行白名单
    if (this.hasUrl(this.urlList, request.url)) return true

    const noCheck = this.reflector?.get<string[]>('isPublic', ctx.getHandler())
    if (noCheck) return true

    return super.canActivate(ctx)
  }

  private urlList: string[] = ['/auth/login', '/auth/register', '/']

  private hasUrl(urlList: string[], url: string): boolean {
    return urlList.includes(url)
  }
}
